import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/picker.dart';
import 'package:my_app_01/api/user.dart';
import 'package:my_app_01/components/MShimmer.dart';
import 'package:my_app_01/components/TagSelect.dart';
import 'package:my_app_01/config.dart';
import 'package:my_app_01/model/User.dart';
import 'package:my_app_01/pages/common/info_input.dart';
import 'package:my_app_01/pages/routes.dart';
import 'package:my_app_01/utils/auth.dart';
import 'package:nil/nil.dart';

class PersonInfoPage extends StatefulWidget {
  const PersonInfoPage({super.key});

  @override
  State<PersonInfoPage> createState() => _PersonInfoPageState();
}

class _PersonInfoPageState extends State<PersonInfoPage> {
  late UserModel userInfo;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        surfaceTintColor: Colors.white,
        elevation: 6,
        shadowColor: Colors.black26,
        title: const Text("个人中心"),
        centerTitle: true,
      ),
      body: FutureBuilder(
        future: UserApi.getUserInfoById({'id': LoginPrefs.getUserInfo()?.id}),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const MShimmer(
              width: double.infinity,
              height: 180,
              margin: EdgeInsets.only(top: 10),
            );
          }
          if (snapshot.connectionState == ConnectionState.done) {
            userInfo = UserModel.fromJson(snapshot.data?['data']);
            userInfo.roleList = LoginPrefs.getUserInfo()?.roleList;
            return ListView(
              children: [
                Container(
                  padding: const EdgeInsets.only(left: 15, right: 15),
                  decoration: const BoxDecoration(color: Colors.white),
                  child: Column(
                    children: ListTile.divideTiles(
                      context: context,
                      color: const Color.fromRGBO(241, 242, 243, 100),
                      tiles: [
                        ListTile(
                          title: const Text("头像"),
                          trailing: Wrap(
                            crossAxisAlignment: WrapCrossAlignment.center,
                            children: [
                              CircleAvatar(
                                backgroundImage: NetworkImage("${MyConfig.fileUrl}${userInfo.avatarurl}"),
                              ),
                              const Icon(
                                Icons.keyboard_arrow_right,
                                color: Colors.black45,
                              ),
                            ],
                          ),
                          onTap: () {
                            EasyLoading.showToast("你点击了xxx");
                          },
                        ),
                        ListTile(
                          title: const Text("账号"),
                          trailing: Text(
                            userInfo.account!,
                            style: const TextStyle(color: Colors.black45),
                          ),
                        ),
                        ListTile(
                          title: const Text("机构"),
                          trailing: Text(
                            userInfo.departname!,
                            style: const TextStyle(color: Colors.black45),
                          ),
                        ),
                        TextListTitle(label: "姓名", value: userInfo.name, type: 'text'),
                        TextListTitle(
                            label: "性别",
                            value: userInfo.sextype,
                            type: 'picker',
                            columns: const ['男', '女'],
                            onChanged: (value) {
                              userInfo.sextype = value['index'];
                            }),
                        TextListTitle(
                            label: "生日",
                            value: userInfo.birthday,
                            type: 'datetime',
                            onChanged: (value) {
                              userInfo.birthday = value;
                            }),
                        TextListTitle(
                            label: "邮箱",
                            value: userInfo.email,
                            type: 'text',
                            onChanged: (value) {
                              userInfo.email = value;
                            }),
                        TextListTitle(
                            label: "手机号码",
                            value: userInfo.mobile,
                            type: 'text',
                            onChanged: (value) {
                              userInfo.mobile = value;
                            }),
                        TextListTitle(
                            label: "联系地址",
                            value: userInfo.address,
                            type: 'text',
                            onChanged: (value) {
                              userInfo.address = value;
                            }),
                        TextListTitle(
                            label: "个人简介",
                            value: userInfo.column1,
                            type: 'text',
                            onChanged: (value) {
                              userInfo.column1 = value;
                            }),
                      ],
                    ).toList(),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.all(15),
                  margin: const EdgeInsets.only(top: 20),
                  decoration: const BoxDecoration(color: Colors.white),
                  child: Row(
                    children: [
                      const Expanded(flex: 1, child: Text("我的角色")),
                      Expanded(
                        flex: 4,
                        child: Wrap(
                          children: userInfo.roleList!.map((e) {
                            return TagItem(
                              name: e.name!,
                            );
                          }).toList(),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.only(left: 10, right: 10),
                  margin: const EdgeInsets.only(top: 20),
                  height: 50,
                  child: ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        const RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(8)),
                        ),
                      ),
                      foregroundColor: MaterialStateProperty.all(Colors.white),
                      backgroundColor: MaterialStateProperty.all(Colors.teal),
                    ),
                    onPressed: () async {
                      EasyLoading.show(status: "保存中...");
                      var data = await UserApi.updateUserInfo(userInfo);
                      Future.delayed(const Duration(milliseconds: 500), () {
                        if (data['status'] == 0) {
                          EasyLoading.showSuccess(data['message'] ?? "保存成功！");
                        }
                      });
                    },
                    child: const Text(
                      '保 存',
                      style: TextStyle(fontSize: 18),
                    ),
                  ),
                ),
              ],
            );
          }
          return nil;
        },
      ),
    );
  }

  void showCupertinoAlertDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: const Text("退出登录"),
            content: const Column(
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                Align(
                  alignment: Alignment(0, 0),
                  child: Text("确定要退出登录吗？"),
                ),
              ],
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: const Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: const Text("确定"),
                onPressed: () {
                  Navigator.of(context).pushNamedAndRemoveUntil(RouterTable.loginPath, (Route route) => false);
                },
              ),
            ],
          );
        });
  }
}

class TextListTitle extends StatefulWidget {
  TextListTitle({
    super.key,
    required this.label,
    this.value,
    this.type,
    this.columns,
    this.onChanged,
  });

  final String label;
  dynamic value;

  final String? type;
  // 当type为picker时需传入该字段作为选项
  List? columns;

  // 值变动后事件
  final ValueChanged<dynamic>? onChanged;

  @override
  State<TextListTitle> createState() => _TextListTitle();
}

class _TextListTitle extends State<TextListTitle> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(widget.label),
      trailing: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            widget.value ?? "暂无${widget.label}信息",
            style: const TextStyle(color: Colors.black45, fontSize: 14),
          ),
          const Icon(
            Icons.keyboard_arrow_right,
            color: Colors.black45,
          ),
        ],
      ),
      onTap: () async {
        if (widget.type == 'text') {
          var result = await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                return TextInputPage(
                  label: widget.label,
                  value: widget.value ?? "",
                );
              },
            ),
          );
          if (widget.onChanged != null) {
            setState(() {
              widget.value = result['value'];
              widget.onChanged!(result['value']);
            });
          }
        } else if (widget.type == 'picker') {
          Picker picker = Picker(
              adapter: PickerDataAdapter<String>(pickerData: widget.columns),
              changeToFirst: true,
              textAlign: TextAlign.left,
              columnPadding: const EdgeInsets.all(8.0),
              confirmText: "确认",
              cancelText: "取消",
              onConfirm: (Picker picker, List value) {
                setState(() {
                  widget.value = picker.getSelectedValues()[0].toString();
                  widget.onChanged!({
                    'index': value[0].toString(),
                    'value': picker.getSelectedValues()[0].toString(),
                  });
                });
              });
          picker.showModal(context);
          // CupertinoPicker
        } else if (widget.type == 'date' || widget.type == 'datetime') {
          String formatStr = widget.type == 'date' ? 'yyyy年 MM月 dd日' : 'yyyy年 MM月 dd日 HH时 mm分 ss秒';
          DatePicker.showDatePicker(
            context,
            dateFormat: formatStr, //通过空格设置滚轮数量
            pickerTheme: DateTimePickerTheme(
              //样式设置，可以设置确认按钮、取消按钮、标题等
              confirm: Text("确认", style: TextStyle(fontSize: 14, color: MyConfig.primaryColor)),
            ),
            onConfirm: (DateTime dateTime, List<int> selectedIndex) {
              var value = dateTime.toString().substring(0, widget.type == 'date' ? 10 : 19);
              // 确认按钮回调，获取选择结果 dateTime
              setState(() {
                widget.value = value;
                widget.onChanged!(value);
              });
            },
          );
        }
      },
    );
  }
}
